let Consts = {
	OpenDataKeys: {
		InitKey: "initKey",
		Grade: "testkey",
		LevelKey: "reachlevel",
		ScoreKey: "levelScore", // json.string
	},
	DomainAction: {
		FetchFriend: "FetchFriend",
		FetchGroup: "FetchGroup",
		FetchFriendLevel: "FetchFriendLevel", //好友关卡进度排行
		FetchFriendScore: "FetchFriendScore", //好友关卡得分排行
		HorConmpar: "HorConmpar", //横向比较 horizontal comparison
		Paging: "Paging",
		Scrolling: "Scrolling"
	},
}

// 这个换成自己的逻辑
let utils = {
    curLevel : 1,
    getScore : _=>{return 1}
}

import Global = require("./GlobalEvents");

const {ccclass, property} = cc._decorator;

@ccclass
export default class RankListMain extends cc.Component {

    @property(cc.Sprite)
    rankRender:cc.Sprite=null; // render spr
    @property(cc.Node)
    rankListNode:cc.Node=null;
    @property(cc.Node)
    rankBgNode:cc.Node=null;    
    @property(cc.Node)
    touchLayer:cc.Node=null;

    enableScroll = true;

    _timeCounter=0;
    rendInterval=0.5;//刷新排行画布间隔s

    rankTexture:cc.Texture2D=null;
    rankSpriteFrame : cc.SpriteFrame=null;

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        this._timeCounter = 0
        this.rankTexture = new cc.Texture2D();
        this.rankSpriteFrame = new cc.SpriteFrame();
        this.resizeSharedCanvas(this.rankRender.node.width, this.rankRender.node.height);
        //上传积分
        if(Global.Score > Global.BestScore)
        {
            Global.BestScore = Global.Score;
            this.uploadScore(1, Global.BestScore);
        }        
        

    }

    start () {
        this.loadLevelScoreRank(1);
    }

    update (dt) {
        this.updateRankList();
    }

    resizeSharedCanvas(width, height){
        console.log(width, height, "====")
        if(!window["wx"]) return;
        let sharedCanvas = window["wx"].getOpenDataContext().canvas;
        sharedCanvas.width = width;
        sharedCanvas.height = height;
        console.log(sharedCanvas);
    }


    updateRankList() {
        if(!window["wx"]) return;
        if(!this.rankTexture) return;
        let sharedCanvas = window["wx"].getOpenDataContext().canvas;
        this.rankTexture.initWithElement(sharedCanvas);
        this.rankTexture.handleLoadedTexture();
        this.rankSpriteFrame.setTexture(this.rankTexture);
        this.rankRender.spriteFrame = this.rankSpriteFrame;
    }

    onEnable() {
        this.touchLayer.active = true;
        if (this.enableScroll) {
            this.rankRender.node.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
        }

        // this.postMessage(Consts.DomainAction.FetchFriendLevel)
    }

    onDisable() {
        if (this.enableScroll) {
            this.rankRender.node.off(cc.Node.EventType.TOUCH_MOVE);
        }
    }

    onViewDetailRank(){        
        this.loadLevelScoreRank(utils.curLevel);
    }

    onPageUp() {
        cc.log(this);
        this.postMessage("Paging", -1);
    }

    onPageDown() {
        this.postMessage("Paging", 1);
    }

    onTouchMove(event) {
        const deltaY = event.getDeltaY();
        // console.log("rank touchmove:", deltaY);
        this.postMessage("Scrolling", deltaY);
    }

    //获取关卡得分排行
    loadLevelScoreRank(level){
        //this.labelTitle.string = `第${level}关排行`
        this.node.active = true;
        this.touchLayer.active = true;
        this.onEnable();        
        this.postMessage(Consts.DomainAction.FetchFriendScore, level);
    }

    //获取关卡进度排行
    loadLevelOpenRank(){
        //this.labelTitle.string = "关卡排行"
        this.node.active = true;
        this.touchLayer.active = true;
        this.onEnable();        
        this.postMessage(Consts.DomainAction.FetchFriendLevel);
    }
    

    //向子域发送消息
    postMessage(action, data=null, dataEx=null) {
        if(!window["wx"]) return;
        let openDataContext = window["wx"].getOpenDataContext();
        openDataContext.postMessage({
            action: action,
            data: data,
            dataEx:dataEx,
        });
    }

    // //检查得分
    // checkScore(key, callback){
    //     if (!window.wx) return
    //     wx.getUserCloudStorage({
    //         keyList:[key],
    //         success:res=>{
    //             res.data.
    //         }
    //     })
    // }

    //wx api
    // 上传关卡分数
    uploadScore(level, score) {
        if(!window["wx"]) return;
        score = score.toString();
        window["wx"].setUserCloudStorage({
            KVDataList: [
                { key: Consts.OpenDataKeys.ScoreKey+level, value: score },
            ],
            success: (res) => {
                console.log("uploadScore success:res=>", res);
            },
            fail: (res) => {
                console.log("uploadScore fail:res=>", res);
            }
        });
    }

    // 上传关卡开启进度
    uploadLevelOpen(level){
        if (!window.window["wx"]) return;
        level = level.toString();
        window["wx"].setUserCloudStorage({
            KVDataList: [
                { key: Consts.OpenDataKeys.LevelKey, value: level },
            ],
            success: (res) => {
                console.log("uploadScore success:res=>", res)
            },
            fail: (res) => {
                console.log("uploadScore fail:res=>", res)
            }
        });
    }

    //删除微信数据
    removeUserKey(key_or_keys) {
        if (!window.window["wx"]) return;
        if(typeof(key_or_keys)==="string"){
            key_or_keys = [key_or_keys];
        }
        window["wx"].removeUserCloudStorage({
            keyList: key_or_keys,
            success: (res) => {
                console.log("uploadScore success:res=>", res)
            },
            fail: (res) => {
                console.log("uploadScore fail:res=>", res)
            }
        });
    }
}
